

import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.UIManager;

import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;



public class Main extends JFrame implements ActionListener{// implements XBeeConnection, SerialPortEventListener{

	private JPanel contentPane;
	private EmbeddedMediaPlayer mediaPlayer;
	private Transceiver txrx;
	private DockingCircle dock;

	VideoDisplay vlcPanel;
	Panel mapPanel;
	JProgressBar progressBar;
	VideoProcessor imageProcessor;
	WeatherRadar radar;
	ControlFrame controlFrame;
	
	final int mainxoffset = 10;
	final int mainyoffset = 40;
	final int mainxsize = 563;
	final int mainysize = 518;
	final int displayxoffset = 583;
	final int displayyoffset = 329;
	final int displayxsize = 250;
	final int displayysize= 229;
	
	public String editor = "";
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		
		
		
		
		
		
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
				
					Main frame = new Main();
					frame.setVisible(true);
					//frame.mediaPlayer.playMedia("C:\\Users\\mfelizola\\Downloads\\20051210-w50s.flv");
					//frame.mediaPlayer.setRepeat(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	
	public int state = StateList.SEQUENCE;//state modified by radio buttons for each function
	
	
	
	//function buttons
	/*JButton newPoint_Button;
	JButton removePoint_Button;
	JButton connectPoints_Button;
	JButton removeLine_Button;
	JButton sequence_Button;
	JButton freeHand_Button;
	*/
	
	//ButtonGroup functionGroup;
	JButton btnNew;
	JButton button;
	JButton button_8;
	JButton button_9; 
	JButton button_1;
	JButton btnFunction;
	JButton button_2;
	JButton radarButton ;
	JButton button_4;
	JButton button_5 ;
	JButton button_6;
	JButton switchButton ;
	JEditorPane editorPane;
	

public void notify(String message) {
		//custom title, warning icon
		JOptionPane.showMessageDialog(this,
		    message,
		    "Error",
		    JOptionPane.WARNING_MESSAGE);
		
	}
    
	

	/**
	 * Create the frame.
	 * @throws IOException 
	 */
	public Main() throws IOException {
		
		//initLookAndFeel();
		this.setAlwaysOnTop(true);
		populateGUI();
		dock = new DockingCircle(this);
		radar = new WeatherRadar(this);
		(new Thread(txrx = new Transceiver(9600,"COM4",this))).start();
		(new Thread(imageProcessor = new VideoProcessor(this))).start();
		
	}


	public void swapVideoMap(){
		if(mapPanel.getBounds().x == mainxoffset){
			mapPanel.setBounds(displayxoffset,displayyoffset,displayxsize,displayysize);
			vlcPanel.setBounds(mainxoffset,mainyoffset,mainxsize,mainysize);
			vlcPanel.sizex = mainxsize;
			vlcPanel.sizey = mainysize;
		} else {
			mapPanel.setBounds(mainxoffset,mainyoffset,mainxsize,mainysize);
			vlcPanel.setBounds(displayxoffset,displayyoffset,displayxsize,displayysize);
			vlcPanel.sizex = 300;
			vlcPanel.sizey = 229;
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {//change this to switches : TO-DO
		if(e.getSource() == btnNew){
			state = StateList.SEQUENCE;
			System.out.println("Sequence");
			
		}else if(e.getSource() == button){
			state = StateList.FREE_HAND;
			System.out.println("Free hand");
			
		}else if(e.getSource() == button_8){
			state = StateList.NEW_POINT;
			System.out.println("New Point");

		}else if(e.getSource() == button_9){
			state = StateList.REMOVE_LINE;
			System.out.println("Remove Line");

		}else if(e.getSource() == button_1){
			state = StateList.REMOVE_POINT;
			System.out.println("Remove Point");

		}else if(e.getSource() == radarButton){
			
			if(radar.radarMap == null){
					radar.launchMap();
			}else{
					radar.close();
			}
			
		}else if(e.getSource() == switchButton){

			swapVideoMap();
			
			System.out.println("switch!");
			
			contentPane.add(vlcPanel);
			contentPane.add(mapPanel);
			contentPane.repaint();
			vlcPanel.repaint();
		}else if(e.getSource() == btnFunction){
			
			if(mapPanel.closedLoop){
				Point[] route = mapPanel.pointList.toArray(new Point[mapPanel.pointList.size()]);
				txrx.txPacket = route;
				txrx.txType = TxType.route;
				//txrx.stopRX();//stopRX triggers tx
				transmit();
			}else{
				this.notify(Messages.OPENLOOP);
			}
		}else if(e.getSource() == button_2){
			JFileChooser fc = new JFileChooser();
			
			   int returnVal = fc.showOpenDialog(Main.this);

	            if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File file = fc.getSelectedFile();
	                System.out.println(file.getAbsolutePath() + " " + file.getName());
	               
	                //This is where a real application would open the file.
	               // log.append("Opening: " + file.getName() + "." + newline);
	            }// else {
	            //    log.append("Open command cancelled by user." + newline);
	            //}
	            //log.setCaretPosition(log.getDocument().getLength());

		}//Handle open button action.
        /*if (e.getSource() == openButton) {
            int returnVal = fc.showOpenDialog(FileChooserDemo.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                log.append("Opening: " + file.getName() + "." + newline);
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());

        //Handle save button action.
        } else if (e.getSource() == saveButton) {
            int returnVal = fc.showSaveDialog(FileChooserDemo.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would save the file.
                log.append("Saving: " + file.getName() + "." + newline);
            } else {
                log.append("Save command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());
        }*/else if(e.getSource() == button_6){
        	controlFrame = new ControlFrame(this);
        }
		
	}
	
	public void startRX(){
		txrx.RX = true;
	}
	
	public void detected(long timeStamp){
		this.mapPanel.markMotion(timeStamp);
	}
	
	public void setPane(String msg){
		editor = editor + "\n\n" + msg;
		editorPane.setText(editor);
	}
	public void GPSupdate(float _latitude, float _longitude){
		mapPanel.gpsReceived(_latitude, _longitude);
	}
	public void showImage(BufferedImage img){
		this.vlcPanel.videoFeed = img;
		this.vlcPanel.repaint();
	}
	
	public void populateGUI() throws IOException{
		Image img;
		//GUI SET UP -----------------------------------------------
				setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				setBounds(100, 100, 851, 596);
				contentPane = new JPanel();
				//contentPane.setBorder(new EmptyBorder(5, 10, 5, 2));
				//contentPane.setLayout(new BorderLayout(0, 0));
				contentPane.setLayout(null);

				setContentPane(contentPane);
				
				progressBar = new JProgressBar();
				progressBar.setBounds(632, 5, 200, 16);
				contentPane.add(progressBar);
				progressBar.setString("Progress");
				progressBar.setStringPainted(true);
				JSeparator separator = new JSeparator();
				separator.setBounds(10, 30, 823, 2);
				contentPane.add(separator);
				
				JSeparator separator_1 = new JSeparator();
				separator_1.setBounds(492, 30, 1, 2);
				contentPane.add(separator_1);
				
				JScrollPane scrollPane = new JScrollPane();
				scrollPane.setBounds(633, 43, 200, 275);
				contentPane.add(scrollPane);
				
				editorPane = new JEditorPane();
				editorPane.setEditable(false);
				scrollPane.setViewportView(editorPane);
				
				
				mapPanel = new Panel(this);
				mapPanel.setBounds(10, 40, mapPanel.sizeX, mapPanel.sizeY);
				contentPane.add(mapPanel);
				
				btnNew = new JButton();
				btnNew.setBounds(583, 43, 40, 23);//setBounds(10, 0, 64, 23);
				btnNew.addActionListener(this);
				img = ImageIO.read(new File("res//buttons//sequence.png"));
			    btnNew.setIcon(new ImageIcon(img));
				contentPane.add(btnNew);
				
				button = new JButton();
				button.setBounds(583, 77, 40, 23);//setBounds(84, 0, 64, 23);
				button.addActionListener(this);
				img = ImageIO.read(new File("res//buttons//freehand.png"));
			    button.setIcon(new ImageIcon(img));
				contentPane.add(button);
				
				button_8 = new JButton();
				button_8.setBounds(583, 111, 40, 23);//setBounds(232, 0, 64, 23);
				button_8.addActionListener(this);
				img = ImageIO.read(new File("res//buttons//newpoint.png"));
			    button_8.setIcon(new ImageIcon(img));
				contentPane.add(button_8);
					
				button_9 = new JButton("L");
				button_9.setBounds(306, 0, 64, 23);
				button_9.addActionListener(this);
				contentPane.add(button_9);
				
				button_1 = new JButton("P");
				button_1.setBounds(158, 0, 64, 23);
				button_1.addActionListener(this);
				contentPane.add(button_1);
				
				btnFunction = new JButton("6");
				btnFunction.setBounds(10, 0, 64, 23);//setBounds(583, 43, 40, 23);
				btnFunction.addActionListener(this);
				contentPane.add(btnFunction);
				
				button_2 = new JButton("7");
				button_2.setBounds(84, 0, 64, 23);//setBounds(583, 77, 40, 23);
				button_2.addActionListener(this);
				contentPane.add(button_2);
				
				radarButton = new JButton("8");
				radarButton.setBounds(232, 0, 64, 23);//setBounds(583, 111, 40, 23);
				contentPane.add(radarButton);
				radarButton.addActionListener(this);
				
				button_4 = new JButton("9");
				button_4.setBounds(583, 145, 40, 23);
				contentPane.add(button_4);
				
				button_5 = new JButton("10");
				button_5.setBounds(583, 179, 40, 23);
				contentPane.add(button_5);
				
				button_6 = new JButton("11");
				button_6.setBounds(583, 213, 40, 23);
				button_6.addActionListener(this);
				contentPane.add(button_6);
				
				switchButton = new JButton("12");
				switchButton.setBounds(583, 295, 40, 23);
				switchButton.addActionListener(this);
				contentPane.add(switchButton);
				
				//VideoPlayer vlcPanel = new VideoPlayer();
				//vlcPanel = new Canvas();
				vlcPanel = new VideoDisplay();
				
				
				
				/*
				NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
				MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
				CanvasVideoSurface videoSurface = mediaPlayerFactory.newVideoSurface(vlcPanel);
				mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
				mediaPlayer.setVideoSurface(videoSurface);
				 */
				vlcPanel.setBounds(583, 329, 250, 229);
				contentPane.add(vlcPanel);

			  //END GUI SET UP--------------------------------------------------
				
				
	}
	
	public void noCamera(){
		this.vlcPanel.noCamera();
	}

	
	public void findLandingPad(){
		
		if(this.imageProcessor.landing == true){			
			dock.getUpdate();
		}else{
			this.imageProcessor.landing = true;			
		}
		
	}
	
	public void sendDockingOffset(){
		this.txrx.dockingCircle = dock.XY;
		this.txrx.txType = TxType.dockingData;
		transmit();
	}

	public void sendNoDock(){
		this.txrx.txType = TxType.dockNotFound;
		transmit();
	}

	public void noDockDetected() {
		dock.notDetected();
		
	}
	
	public void dockDetected(int _x, int _y, int radius,int _screenX, int _screenY){
		dock.update(_x, _y, radius, _screenX, _screenY);
	}
	
	public void transmit(){
		
		if(txrx.RX != false){
			
			txrx.RX = false;
			
		} else {
			
			setPane(Messages.TXRXCLASH);
			
		}
		
	}
	
	public void control(byte parameter){
		
		this.txrx._parameter = parameter;
		transmit();
		
	}
	
	
}



